package com.maodou.android.ui.page.search

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.KeyboardArrowLeft
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.maodou.android.ui.page.AccountDetailKey
import com.maodou.android.ui.page.EditAccountKey
import com.maodou.android.ui.page.home.AccountCard
import com.maodou.android.ui.page.home.SwipeRevealContainer
import com.maodou.android.viewmodel.account.AccountViewModel
import com.maodou.core.navigation.Navigator3
import com.maodou.core.ui.components.ActionBar
import com.maodou.core.ui.components.TitleAlignment
import com.maodou.core.ui.components.VSpacer
import com.maodou.core.utils.Logger

/**
 * @Author Xing
 * @CreateTime 2025年09月17日
 * @Description 账号搜索页面
 */
@Composable
fun SearchScreen(
    viewModel: AccountViewModel = hiltViewModel(),
) {

    val focusManager = LocalFocusManager.current
    var query by rememberSaveable { mutableStateOf("") }
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()

    val lifecycleOwner = LocalLifecycleOwner.current
    DisposableEffect(lifecycleOwner) {

        val observer = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_START -> {

                }

                Lifecycle.Event.ON_RESUME -> {

                }

                Lifecycle.Event.ON_PAUSE -> {

                }

                Lifecycle.Event.ON_STOP -> {
                    viewModel.clearTableData()
                }

                Lifecycle.Event.ON_DESTROY -> {
                }

                else -> {}
            }
        }

        lifecycleOwner.lifecycle.addObserver(observer)

        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }

    Column(modifier = Modifier.fillMaxSize()) {
        ActionBar(
            title = "搜索",
            modifier = Modifier.fillMaxWidth(),
            navigationIcon = Icons.AutoMirrored.Outlined.KeyboardArrowLeft,
            onNavigationClick = {
                Navigator3.pop()
            },
            backgroundColor = Color.Transparent,
            contentColor = MaterialTheme.colorScheme.onSurface,
            titleAlignment = TitleAlignment.Center,
        )

        // 搜索输入框
        OutlinedTextField(
            value = query,
            onValueChange = {
                query = it
                viewModel.onSearchAccount(query)
            },
            textStyle = LocalTextStyle.current.copy(lineHeight = 14.sp),
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp),
            placeholder = { Text(text = "搜索账号/昵称/ID/标签") },
            singleLine = true,
            shape = RoundedCornerShape(32.dp),
            leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
            trailingIcon = {
                if (query.isNotEmpty()) {
                    IconButton(onClick = {
                        query = ""
                        viewModel.onSearchAccount("")
                        focusManager.clearFocus()
                    }) {
                        Icon(Icons.Filled.Close, contentDescription = "清空")
                    }
                }
            },
            keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search)
        )

        VSpacer(12.dp)

        val list = uiState.searchAccountData
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(horizontal = 16.dp),
            contentPadding = PaddingValues(bottom = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding() + 16.dp),
        ) {
            items(
                items = list,
                key = { it.accountID }
            ) { item ->
                SwipeRevealContainer(
                    enableSwipe = true,
                    onEdit = { Navigator3.navigate(EditAccountKey(item)) },
                    onDelete = { viewModel.onDeleteAccount(arrayListOf(item)) },
                    onItemLongPress = null,
                    onItemClick = {
                        Navigator3.navigate(AccountDetailKey(item))
                    }
                ) {
                    AccountCard(
                        item = item,
                        selectionMode = false,
                        onSelect = {}
                    ){
                    }
                }
            }
        }
    }
}